package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.*;
import com.itheima.entity.vo.PmsProductVo;
import com.itheima.jsonresult.JsonResult;
import com.itheima.mapper.PmsProductMapper;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author linying
 * @since 2022-10-13
 */
@Service
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements PmsProductService {

    @Autowired
    private PmsMemberPriceService memberPriceService;

    @Autowired
    private PmsProductLadderService productLadderService;

    @Autowired
    private PmsProductFullReductionService productFullReductionService;

    @Autowired
    private PmsSkuStockService skuStockService;


    /**
     * 添加商品信息
     * @param productVo
     * @return
     */
    @Override
    public JsonResult addProduct(PmsProductVo productVo) {
        //创建新的productAttribute装数据
        PmsProduct product = new PmsProduct();
        //复制
        BeanUtil.copyProperties(productVo, product);
        //取出另外3个信息
        //阶梯价格
        PmsProductLadder productLadder = productVo.getProductLadder();
        //设置id为商品的id
        productLadder.setProductId(product.getId());
        //满减价格
        PmsProductFullReduction productFullReduction = productVo.getProductFullReduction();
        productFullReduction.setProductId(product.getId());
        //会员价格
        PmsMemberPrice memberPrice = productVo.getMemberPrice();
        memberPrice.setProductId(product.getId());
        //SUK
        PmsSkuStock skuStock = productVo.getSkuStock();
        skuStock.setProductId(product.getId());

        // 根据username查询是否存在
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("name", product.getName());

        // 查询结果为空，不存在
        if ((getOne(wrapper) == null)) {
            // 添加商品属性
            save(product);
            //添加会员价格
            memberPriceService.save(memberPrice);
            //添加阶梯价格
            productLadderService.save(productLadder);
            //添加满减价格
            productFullReductionService.save(productFullReduction);
            //添加SKU
            skuStockService.save(skuStock);

            return new JsonResult(1, null, "添加商品属性成功", null);
        } else {
            return new JsonResult(0, null, product.getName() + "已存在", null);
        }
    }
}
